// import Timer from "../utils/Timer";
import fs from "fs";
import * as pako from "../out/pako";

const RECORD_FILE = "./gdata";
const RECORD_VERSION_KEY = "__version__";
/**
 * 存档版本号：
 * 1： 2018-6-21：未知不兼容现象，强制清档
 */
const RECORD_VERSION_VALUE = 0;


export default class mgrRecord {
    ///// 成员变量 /////

    /**
     * 核心存档数据
     * {key:value}
     */
    private static record: any = {};

    private static bNeedFlush: boolean = false;








    ///// 生命周期 /////
    public static onload(): void {
        // 加载存档
        this._readRecord();
        console.log("recored inited.");
    }










    ///// IO相关 /////
    /**
     * 读取存档
     */
    private static _readRecord(recordText?: string) {
        if (!recordText) {
            try {
                recordText = fs.readFileSync(RECORD_FILE, "utf8");
            } catch (error) {
                console.log("read err:", error);
            }
        }
        // cc.log("recordText", recordText);

        if (!recordText) {
            console.warn("警告] mgrRecord._readRecord 存档未找到！重置存档！");
            this.resetRecord();
            return;
        }

        let record: any;
        try {
            record = this.decodeData(recordText);
        } catch (error) {
            console.log("兼容老数据格式.");
            record = JSON.parse(recordText);
        }

        if (!record) {
            console.warn("警告] mgrRecord._readRecord 存档数据损坏！重置存档！");
            this.resetRecord();
            return;
        }

        if (record[RECORD_VERSION_KEY] != RECORD_VERSION_VALUE) {
            console.warn("警告] mgrRecord._readRecord 存档版本改变！重置存档！");
            this.resetRecord();
            return;
        }

        this.record = record;
    }


    /**
     * 写入存档（内部实现）
     */
    private static _writeRecord() {
        // cc.log("mgrRecord._writeRecord");
        let recordText = this.getAllDataStr();
        fs.writeFileSync(RECORD_FILE, recordText, { encoding: "utf8" });
    }


    public static getAllDataStr() {
        return this.encodeData(this.record);
    }


    /** 获取存档的json格式数据 */
    public static getAllJsonStr() {
        return JSON.stringify(this.record);
    }


    /** 从外部写入存档 */
    public static readFromJsonStr(jsonStr: string) {
        try {
            let data = JSON.parse(jsonStr);
            this.record = data;
            console.log("readFromJsonStr suc.");
        } catch (error) {
            console.log("readFromJsonStr fail.");
        }
    }


    /**
     * 请求写入存档（不会立即执行）
     */
    private static _requestFlush() {
        // this.bNeedFlush = true;
        this._writeRecord();
    }


    public static forceWrite() {
        this._writeRecord();
    }



    ///// 存取接口 /////
    /**
     * 读取存档数据
     * @param key
     */
    public static getData(key: string): any {
        return this.record[key];
    }


    /**
     * 设置存档数据
     * @param key 
     * @param value 
     */
    public static setData(key: string, value: Object) {
        this.record[key] = value;
        this._requestFlush();
    }


    /**
     * 重置存档
     */
    public static resetRecord() {
        this.record = {};
        this.record[RECORD_VERSION_KEY] = RECORD_VERSION_VALUE;
        this._requestFlush();
    }


    public static encodeData(data: any) {
        let str = JSON.stringify(data);
        return this.compress(str);
    }


    public static decodeData(data: any) {
        let decompressData = this.decompress(data);
        return JSON.parse(decompressData);
    }



    /** 压缩字符串 */
    public static compress(str: string): string {
        return pako.gzip(str, { to: "string" });
    }


    /** 解压字符串 */
    public static decompress(str: string): string {
        return pako.ungzip(str, { to: "string" });
    }


    /** 解压字符串 */
    // public static decompressFromBase64(base64: string): string {
    //     let arr = Base64.decodeToUnit8Array(base64);
    //     return pako.ungzip(arr, { to: "string" });
    // }




}